package com.project.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.project.bean.OrderBean;
import com.project.bean.UserBean;
import com.project.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.time.LocalDate;
import java.util.List;

/**
 * @author lyl
 * description:
 */
@RestController
@RequestMapping("order")
public class OrderController {
    @Autowired
    private IOrderService iOrderService;

    @RequestMapping("add")
    public String add(@Valid OrderBean orderBean, BindingResult bindingResult, HttpServletRequest request) throws JsonProcessingException {
        //执行步骤前先进行错误信息判断
        if (bindingResult.hasErrors()) {
            //如果有错误的信息则将字符串返回到页面
            List<FieldError> error = bindingResult.getFieldErrors();
            String str = new ObjectMapper().writeValueAsString(error);
            return str;
        }


        UserBean userBean = (UserBean) request.getSession().getAttribute("userBean");
        System.out.println(orderBean);
        iOrderService.addNewOrder(orderBean, userBean.getUserId());
        return "ok";
    }

    @RequestMapping("findByPage")
    public PageInfo<OrderBean> findByPage(int pageNo, String orderStatue, LocalDate startDate, LocalDate endDate, HttpServletRequest request) {
        UserBean userBean = (UserBean) request.getSession().getAttribute("userBean");
        return iOrderService.findOrderByItem(pageNo, orderStatue, startDate, endDate, userBean.getUserId());
    }

    @RequestMapping("findByPagePro")
    public PageInfo<OrderBean> findByPagePro(int pageNo, String orderStatue, LocalDate startDate, LocalDate endDate) {
        return iOrderService.findOrderByStatue(pageNo, orderStatue, startDate, endDate);
    }

    @RequestMapping("findOrderInfo")
    public OrderBean findOrderInfo(int orderId) {
        return iOrderService.findByOrderId(orderId);
    }

    @RequestMapping("updatePro")
    public String updatePro(int orderId) {
        iOrderService.proUserUpdateOrderStatue(orderId);
        return "ok";
    }

    @RequestMapping("updatePost")
    public String updatePost(int orderId) {
        iOrderService.postUserUpdateOrderStatue(orderId);
        return "ok";
    }
}
